# -*- coding: utf-8 -*-
import json
import logging
from scrapy.utils.project import get_project_settings
from zc_core.client.redis_client import Redis

logger = logging.getLogger('CookieDao')


class CookieDao(object):
    """
    批次操作简易封装（MongoDB）
    """

    def save_cookie(self, cookies, key=None, expire_time=7200):
        try:
            if not cookies:
                logger.info('no cookies to save...')
                return
            if not key:
                settings = get_project_settings()
                key = 'zc:cookie:{}'.format(settings.get('BOT_NAME'))
            if cookies and not isinstance(cookies, str):
                cookies = json.dumps(cookies)
            Redis().client.setex(name=key, time=expire_time, value=cookies)
            logger.info('Redis save cookies [%s -> %s]' % (key, cookies))
        except ConnectionError as e:
            logger.info('Redis connect error: %s' % e)
        except Exception as e:
            logger.info('Redis save error: %s' % e)

    def update_cookie(self, key=None, expire_time=7200):
        try:
            if not key:
                settings = get_project_settings()
                key = 'zc:cookie:{}'.format(settings.get('BOT_NAME'))
            if Redis().client.exists(key):
                Redis().client.expire(name=key, time=expire_time)
            # logger.info('Redis update cookies [%s -> %ss]' % (key, expire_time))
        except ConnectionError as e:
            logger.info('Redis connect error: %s' % e)
        except Exception as e:
            logger.info('Redis save error: %s' % e)

    def delete_cookie(self, key=None):
        try:
            if not key:
                settings = get_project_settings()
                key = 'zc:cookie:{}'.format(settings.get('BOT_NAME'))
            if Redis().client.exists(key):
                Redis().client.delete(key)
            # logger.info('Redis update cookies [%s -> %ss]' % (key, expire_time))
        except ConnectionError as e:
            logger.info('Redis connect error: %s' % e)
        except Exception as e:
            logger.info('Redis save error: %s' % e)

    def get_cookie(self, key=None):
        try:
            if not key:
                settings = get_project_settings()
                key = 'zc:cookie:{}'.format(settings.get('BOT_NAME'))
            cookies = Redis().client.get(key)
            if cookies:
                cookie_json = json.loads(cookies)
                logger.debug('Load cookies from redis [%s -> %s]' % (key, cookie_json))
                return cookie_json
        except ConnectionError as ce:
            logger.info('Redis connect error: %s' % ce)
        except Exception as e:
            logger.info('Redis get error: %s' % e)
        return ''
